package protocol.simp;

import chatty.comm.StringConvertor;
import chatty.comm.Util;
import chatty.modules.*;

import protocol.*;
/**
 *
 * @author Ahmetshin R.U.S.H.A.N.
 */
public class SimpPacket {

    private Util 		outPacket = new Util();
    private int 		type;
	private int 		subtype;
    private int 		dlen;	
	private String		login;
    private byte[] 		inData;
    private int 		inCursor;

    public int getType() {
        return type;
    }
	public int getSubtype() {
        return subtype;
    }
    public byte[] getData() {
        return inData;
    }
	public int getDlen() {
        return dlen;
    }
    public String getUserId() {
        return login;
    }	
	
	public SimpPacket( int type, String login ) {
		this( type, 0, login, null, 0 );
    }
	
    public SimpPacket( int type, int subtype, String login ) {
        this( type, subtype, login, null, 0 );
    }
	
    public SimpPacket( int type, int subtype, String login, byte[] data, int data_size ) {
		inData = data;
        inCursor = 0;
		this.type = type;
		this.subtype = subtype;
		this.login = login;
		this.dlen = data_size;
		
        write_dword( type );
		write_dword( subtype );
        write_str( login, 48 );
        write_dword( 0 ); // dlen
    }
	
	public void write_dword(long data) {

        outPacket.writeDWordLE(data);
    }
	
    public void write_byte_array(byte data[] ) {
        outPacket.writeByteArray( data );
    }
	
	public void write_str( String data, int len ) {
	
		if( data == null ) return;
		
		int string_len = data.length();
		
        outPacket.writeByteArray(StringConvertor.stringToByteArray1251(data), 0, Math.min(len, string_len) );
		
		if( len > string_len ) {
			write_byte_array( new byte[len - string_len] );
		} else {
		}
    }
	
    public int get_dword() {
        long value = Util.getDWordBE(inData, inCursor);
        inCursor += 4;
        return (int)value;
    }
	public String get_str( int len ) {
        String str = null;
		
		if( isEof() )
			return null;
			
		if( (dlen - inCursor - len) < 0 )
			len = dlen - inCursor;
		
		if( inData[inCursor] == 0 ) {
			inCursor += len;
			return null;
		}
        str = StringConvertor.byteArray1251ToString(inData, inCursor, len);
        inCursor += len;
		
        return /*StringConvertor.removeCr(*/str/*)*/;
    }
	
	public byte[] get_byte_array( int len ) {

		if( (dlen - inCursor - len) < 0 )
			len = dlen - inCursor;
		
        byte[] data = new byte[len];
		
		System.arraycopy(inData, inCursor, data, 0, len);

        inCursor += len;
		
        return data;
    }
	public int getLen() {
        return dlen;
    }
	
	public boolean isEof() {
        return dlen <= inCursor;
    }
	
	public byte[] toByteArray() {
	
        byte[] packet = outPacket.toByteArray();
	
		Util.putDWordLE( packet, 56, packet.length - 60 ); // dlen
		
		return packet;
    }
	
    public Util raw() {
        return outPacket;
    }
}